<?php

namespace app\admin\controller\zone;

use think\Config;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 角色管理
 *
 * @icon fa fa-address-card-o
 */
class Char extends Backend
{

    /**
     * Char模型对象
     * @var \app\admin\model\zone\Char
     */
    protected $model = null;

    protected $backTown = [
        '通用大理回城点',
        '通用苏州回城点',
        '通用洛阳回城点',
        '原地不动',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\zone\Char;
        $this->assign('backTown',$this->backTown);
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach ($list as $k => &$v) {
                $tmp = mb_convert_encoding($v['charname'],'ISO-8859-1','UTF-8');
                $tmpTitle = mb_convert_encoding($v['title'],'ISO-8859-1','UTF-8');
                $v['charname'] = mb_convert_encoding($tmp,'UTF-8','gb18030');
                $v['title'] = mb_convert_encoding($tmpTitle,'UTF-8','gb18030');
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //处理回城点配置
                $backTownData = Config::get('site.back_town');
                if ($params['back_town'] != 3) {
                    //表示需要回城操作
                    $backTown = $backTownData[$params['back_town']];
                    $params['xpos'] = explode(',',$backTown)[0];
                    $params['zpos'] = explode(',',$backTown)[1];
                    $params['scene'] = $params['back_town'];
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加方法
     * @internal
     */
    public function add()
    {
        $this->error('不允许直接添加！');
    }

    /**
     * 角色解封
     * @param null $ids
     * @throws \think\exception\DbException
     */
    public function setCharNormal($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $data = '00804F120000040000000100000000000000000000000000000000000000000000000000000000000116000000012300000002010000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FF0000000000000000000000000000F1330000000000000000000000000001E4B6420E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';

        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->isUpdate(true)->save(['settings'=>$data],['aid'=>$ids]);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            return ['msg'=>'解封成功！'];
        } else {
            return ['msg'=>'解封失败！'];
        }
    }

}
